﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CloudFranceTriple.Models;
using Postal;

namespace CloudFranceTriple.WebRole.Areas.Forum.Controllers
{
    /// <summary>
    /// [InitializeSimpleMembership] est utilisé car cette classe peut être appelée
    /// </summary>
    [CloudFranceTriple.WebRole.Filters.InitializeSimpleMembership]
    public class PrivateMessageController : BaseController
    {
        private cloudfrAboq2RsDMEntities db = new cloudfrAboq2RsDMEntities();

        private readonly IWebSecurityWrapper _webSecurity;
        public PrivateMessageController()
        {
            this._webSecurity = new WebSecurityWrapper();
        }

        public PrivateMessageController(IWebSecurityWrapper webSecurity)
            : base(webSecurity)
        {
            this._webSecurity = webSecurity;
        }
        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult MsgToRead()
        {
            if (!User.Identity.IsAuthenticated) return null;
            var _UserId = base.UserId;
            var _toMsg = db.PrivateMessageBoxSet.Where(msg => msg.ToPrivateMessage == _UserId);
            var _MsgToRead = (_toMsg.Count()) - (_toMsg.Join(db.PrivateMessageReadSet.Where(read2 => read2.UserId == _UserId), msg => msg.Id, read => read.PrivateMessageBox_Id, (read, msg) => read.Id).Count());
            return PartialView("_MsgToRead", _MsgToRead);
        }

        //
        // GET: /Forum/PrivateMessage/

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember")]
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Forum/PrivateMessage/

        [ChildActionOnly]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember")]
        public ActionResult PrivateMessageSend()
        {
            var _userId = base.UserId;
            return PartialView("_PrivateMessageSentList", db.PrivateMessageBoxSet.Where(pm => pm.FromPrivateMessage == _userId).OrderByDescending(pm2 => pm2.MessageBody_CreationDate).ToList());
        }

        //
        // GET: /Forum/PrivateMessage/

        [ChildActionOnly]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember")]
        public ActionResult PrivateMessageReceived()
        {
            var _userId = base.UserId;
            var query = db.PrivateMessageBoxSet.Where(pm => pm.ToPrivateMessage == _userId).OrderByDescending(pm3 => pm3.ParentId).OrderByDescending(pm4 => pm4.Id).ToList();
            return PartialView("_PrivateMessageReceivedList", query);
        }

        //
        // GET: /Forum/PrivateMessage/Details/5

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember")]
        public ActionResult Details(int id = 0)
        {
            PrivateMessageBoxSet privatemessageboxset = db.PrivateMessageBoxSet.Find(id);
            if (privatemessageboxset == null || (privatemessageboxset.FromPrivateMessage != base.UserId && privatemessageboxset.ToPrivateMessage != base.UserId))
            {
                return HttpNotFound();
            }
            return View(privatemessageboxset);
        }

        //
        // GET: /Forum/PrivateMessage/Create/UserId

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember")]
        public ActionResult Create(int id = 0, int? id2 = null)
        {
            var uc = new CloudFranceTriple.WebRole.Models.UsersContext();

            ViewBag.ToPrivateMessage = new SelectList(uc.UserProfiles.Where(ul => ul.ShowInNonAdminList).OrderBy(u => u.UserName), "UserId", "UserName", id);
            ViewBag.ParentId = id2;
            if (id2 != null)
            {
                var _originalMessage = db.PrivateMessageBoxSet.Find(db.PrivateMessageBoxSet.Where(pm2 => (pm2.Id == id2) || (pm2.ParentId == id2)).Max(pm => pm.Id));
                var _currentUserId = _webSecurity.CurrentUserId;
                if ((_originalMessage.FromPrivateMessage == _currentUserId) || (_originalMessage.ToPrivateMessage == _currentUserId))
                {
                    ViewBag.OriginalPrivateMessage = _originalMessage.MessageBody_Message;
                    ViewBag.SuggestedSubject = String.Format("Re: {0}", _originalMessage.MessageBody_Label);
                }
                else
                    ThrowSecurityException();
            }
            return View(new PrivateMessageBoxSet { MessageBody_Label = ViewBag.SuggestedSubject });
        }

        //
        // POST: /Forum/PrivateMessage/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember")]
        public ActionResult Create(PrivateMessageBoxSet privatemessageboxset)
        {
            if (ModelState.IsValid)
            {
                var _userFrom = GetProfile();
                var _userTo = GetProfile(privatemessageboxset.ToPrivateMessage);

                privatemessageboxset.FromPrivateMessage = _userFrom.UserId;
                privatemessageboxset.MessageBody_Author = User.Identity.Name;
                privatemessageboxset.MessageBody_AuthorAdressIp = Request.UserHostAddress.Substring(0, Request.UserHostAddress.Length > 15 ? 15 : Request.UserHostAddress.Length);
                privatemessageboxset.MessageBody_CreationDate = DateTime.UtcNow;
                db.PrivateMessageBoxSet.Add(privatemessageboxset);
                db.SaveChanges();

                // Un message est parent de lui meme pour faciliter le tri sur la colonne ParentId
                if (privatemessageboxset.ParentId == null)
                {
                    privatemessageboxset.ParentId = privatemessageboxset.Id;
                    db.SaveChanges();
                }

                //Notifier par email le destinataire
                dynamic email = new Email("NewPrivateMessageEmail");
                email.To = _userTo.Email;
                email.UserName = _userTo.UserName;
                email.PrivateMessageFrom = _userFrom.UserName;
                email.PrivateMessageSubject = privatemessageboxset.MessageBody_Label;
                email.PrivateMesageId = privatemessageboxset.Id;
                email.Send();

                return RedirectToAction("Index", "PrivateMessage", new { area = "Forum" });
            }

            return View(privatemessageboxset);
        }

        //
        // GET: /Forum/PrivateMessage/Delete/5

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember")]
        public ActionResult Delete(int id = 0)
        {
            PrivateMessageBoxSet privatemessageboxset = db.PrivateMessageBoxSet.Find(id);
            if (privatemessageboxset == null)
            {
                return HttpNotFound();
            }
            return View(privatemessageboxset);
        }

        //
        // POST: /Forum/PrivateMessage/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember")]
        public ActionResult DeleteConfirmed(int id)
        {
            PrivateMessageBoxSet privatemessageboxset = db.PrivateMessageBoxSet.Find(id);

            if (privatemessageboxset == null || (privatemessageboxset.ToPrivateMessage != base.UserId))
            {
                return HttpNotFound();
            }


            if (privatemessageboxset.ParentId == null)
            {
                var privatemessageboxchild = db.PrivateMessageBoxSet.Where(msg => msg.ParentId == privatemessageboxset.Id);
                foreach (PrivateMessageBoxSet msg in privatemessageboxchild)
                    db.PrivateMessageBoxSet.Remove(msg);
            }

            db.PrivateMessageBoxSet.Remove(privatemessageboxset);
            db.SaveChanges();
            return RedirectToAction("Index", "PrivateMessage", new { area = "Forum" });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}